package com.dzqc.fly.controller.mobile;

import com.dzqc.fly.common.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by Administrator on 2022-9-7 0007.
 */
@RestController
@RequestMapping(value = "/fileUpload")
public class FileUploadController {

    @Value("${file.upload.dir}")
    private String uploadFilePath;

    SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");

    @RequestMapping("/uploadImg")
    public Result uploadImg(@RequestParam("files")MultipartFile uploadFile, HttpServletRequest req){
        //获取文件名
        String fileName = uploadFile.getOriginalFilename();
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //重新生成文件名
        fileName = UUID.randomUUID()+suffixName;
        //添加日期目录
        String format = sd.format(new Date());
        //指定本地文件夹存储图片
        String filePath = uploadFilePath+"/"+format+"/";
        File file = new File(filePath,fileName);
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        try {
            //将图片保存到static文件夹里
            file.createNewFile();
//            uploadFile.transferTo(new File(filePath+fileName));
            FileUtils.copyInputStreamToFile(uploadFile.getInputStream(),file);
            Result result=Result.ok().put("message","文件上传成功!").put("image",format+"/"+fileName);
            return result;
//            return  format+"/"+fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
